// SnbReader.cpp : Implementation of CSnbExtractor

#include "stdafx.h"
#include "snbextractor.h"
#include "snbdata.h"

// CSnbExtractor
STDMETHODIMP CSnbExtractor::Load(BSTR bstrFile)
{
	m_bstrFile = bstrFile;

	USES_CONVERSION_EX;
	std::string str = OLE2A_EX(m_bstrFile, 0);

	return m_BookReader.Load(str) ? S_OK : E_FAIL;
}

STDMETHODIMP CSnbExtractor::Extract(BSTR bstrPath)
{
	USES_CONVERSION_EX;
	std::string str = OLE2A_EX(bstrPath, 0);	
	
	return m_BookReader.Extract(str) ? S_OK : E_FAIL;
}

STDMETHODIMP CSnbExtractor::GetToc(VARIANT* pvToc)
{
	std::string str;
	if (m_BookReader.GetToc(str))
	{
		pvToc->vt = VT_BSTR;
		pvToc->bstrVal = SysAllocStringByteLen(str.c_str(), str.size());

		return S_OK;
	}

	return E_FAIL;
}

STDMETHODIMP CSnbExtractor::GetDesc(VARIANT* pvDesc)
{
	std::string str;
	if (m_BookReader.GetDesc(str))
	{
		pvDesc->vt = VT_BSTR;
		pvDesc->bstrVal = SysAllocStringByteLen(str.c_str(), str.size());

		return S_OK;
	}

	return E_FAIL;
}

STDMETHODIMP CSnbExtractor::GetChapter(BSTR bstrName, VARIANT* pvChapter)
{
	if (bstrName == NULL)
		return E_FAIL;

	USES_CONVERSION_EX;
	std::string strChapter = OLE2A_EX(bstrName, 0);

	std::string strText;
	if (m_BookReader.GetChapter(strChapter, strText))
	{
		pvChapter->vt = VT_BSTR;
		pvChapter->bstrVal = SysAllocStringByteLen(strText.c_str(), strText.size());

		return S_OK;
	}

	return E_FAIL;
}

STDMETHODIMP CSnbExtractor::GetImage(BSTR bstrName, VARIANT* pvImage)
{	
	if (bstrName == NULL)
		return E_FAIL;

	USES_CONVERSION_EX;
	std::string strImage = OLE2A_EX(bstrName, 0);

	int nSize;
	boost::shared_array<char> pImage;
	
	if (m_BookReader.GetImage(strImage, pImage, nSize))
	{
		pvImage->vt = VT_BSTR;
		BSTR pBuf = SysAllocStringByteLen(NULL, nSize);

		memcpy((char *)pBuf, pImage.get(), nSize);

		pvImage->bstrVal = pBuf;

		return S_OK;
	}

	return E_FAIL;
}

STDMETHODIMP CSnbExtractor::GetSize(LPDWORD pdwFileSize)
{
	if (pdwFileSize)
	{
		return m_BookReader.GetSize(*pdwFileSize);
	}

	return E_FAIL;
}